//
//  PlayerManager.m
//  NewChat
//
//  Created by 马欢 on 16/3/6.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "PlayerManager.h"
#import "MHDataHelper.h"
#import <UIKit/UIKit.h>
#import "UIImageView+WebCache.h"
#import "PlayerViewController.h"
#import "NSString+TimeFormatter.h"

#define HELPER [MHDataHelper shareDataHelper]
#define PLAYER [PlayerViewController sharedPlayerViewController]

@interface PlayerManager ()

@property (nonatomic,strong)NSTimer *timer;//定时器(让代理不断执行协议中的方法)
@property (nonatomic,strong)NSMutableArray *currentArray;
@end

@implementation PlayerManager
//单例
+(instancetype)defaultManager{
    static PlayerManager *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PlayerManager alloc]init];
        manager.playMode =@"xunhuan";//关键，勿忘
    });
    return manager;
}
//===============待修改 添加=============
//准备播放 具体的音乐，数据从dataHelper单例传过来
-(void)prepareMusicWithIndex:(NSInteger)index{
    //    if (_currentIndex != index) {
    //判断网络状态
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    if (status == RealStatusNotReachable){//无网
    }else{//有网=========================????????????
        
        _lastIndex = _currentIndex;
        _currentIndex = index;
        self.currentArray = self.passModels;
        SongModel *song = self.passModels[index];
        //    实例化一个playerItem作为player要播放的歌曲
        AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:[song.urlList[1] valueForKey:@"url"]]];
        //    替换当前播放的playerItem
        [self.player replaceCurrentItemWithPlayerItem:item];
        //   安全判断delegate协议
        if ([_didSkippedSongDelegate respondsToSelector:@selector(didSkippedSong:)]) {
            [_didSkippedSongDelegate didSkippedSong:song];
        }
        [self musicPlay];
    }
    //    }
}

//=================一般不改========================================
//重写init方法
-(instancetype)init{
    self = [super init];
    if(self){
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didMusicPlayFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        _currentIndex = -1;
        _lastIndex = -1;
    }
    return self;
}
//当当前音乐播放完毕时，执行下面这个方法
-(void)didMusicPlayFinished{//待添加播放模式!!!!!!!
    if ([_playMode isEqualToString:@"xunhuan"]) {
        [self nextMusic];
    }else if ([_playMode isEqualToString:@"danqu"]){
        [self playAgain];
    }else if ([_playMode isEqualToString:@"suiji"]){
        [self playRandom];
    }
}
-(void)musicPlay{
    if (_timer == nil) {
        //创建一个定时器，让其0.1秒执行一次方法
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    //播放执行
    [_player play];
}
//定时器响应事件
-(void)timerAction{
    //代理安全判断
    if ([_didSkippedSongDelegate respondsToSelector:@selector(isPlayingMusicAsTime:)]) {
        CGFloat seconds =  CMTimeGetSeconds(self.player.currentTime);//获取当前播放到的时间位置
        [_didSkippedSongDelegate isPlayingMusicAsTime:[NSString getStringFormateByTime:seconds]];
    }
}
//停止播放器
-(void)stopPlay{
    [self pausePlay];
    self.player = nil;
    self.currentIndex = -1;
    self.lastIndex = -1;
}
//上一首
-(void)lastMusic{
    if (_lastIndex != -1 && [self.playMode isEqualToString:@"suiji"]){
        [self prepareMusicWithIndex:_lastIndex];
    }else{
        [self prepareMusicWithIndex:self.currentIndex == 0? self.passModels.count-1:_currentIndex-1];
    }
}
//下一首
-(void)nextMusic{
    if ([_playMode isEqualToString:@"suiji"]){
        [self playRandom];
    }else{
        [self prepareMusicWithIndex:self.currentIndex+1 <self.passModels.count? self.currentIndex+1 : 0];
    }
}
//暂停
-(void)pausePlay{
    [self.timer invalidate];
    _timer = nil;//将定时器去除，用到再创建//优化一下
    [self.player pause];
}
//使用懒加载，创建player对象
-(AVPlayer *)player{
    if (_player == nil) {
        _player = [[AVPlayer alloc]init];
    }
    return _player;
}
-(NSMutableArray *)currentArray{
    if (!_currentArray) {
        _currentArray = [NSMutableArray array];
    }
    return _currentArray;
}
-(NSMutableArray *)passModels{
    if (!_passModels) {
        self.passModels = [NSMutableArray array];
    }
    return _passModels;
}
//随机播放一首歌
-(void)playRandom{
    [self prepareMusicWithIndex:arc4random()%self.passModels.count];
}
//重新准备这首歌
-(void)playAgain{
    SongModel *song = self.passModels[_currentIndex];
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:[song.urlList[1] valueForKey:@"url"]]];
    //    替换当前播放的playerItem
    [self.player replaceCurrentItemWithPlayerItem:item];
    //   安全判断delegate协议
    if ([_didSkippedSongDelegate respondsToSelector:@selector(didSkippedSong:)]) {
        [_didSkippedSongDelegate didSkippedSong:song];//切这首歌
    }
    [self musicPlay];
}
//快进 快退
-(void)musicSeekToTime:(float)time{//time秒数
    //    公式：value/timescale = seconds//秒数
    [self.player seekToTime:CMTimeMake(time*self.player.currentTime.timescale, self.player.currentTime.timescale)];//前value，后timescale
}
@end
